﻿using Microsoft.Practices.EnterpriseLibrary.Data.Sql;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.Data.SqlClient;
using System.Web;
using Easy.Common;
using Easy.BLL;

namespace Easy.Web.Service.Data
{
    /// <summary>
    /// Summary description for GetReportListData
    /// </summary>
    public class GetReportListData : BaseHttpHandler
    {

        public override void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            CustomResult res = new CustomResult();
            try
            {
                string sp = context.Request["sp"];
                if (sp == null || (!sp.StartsWith("sp_rpt_data_")))
                {
                    res.ResultCode = -1;
                    res.ResultMessage = "SP名称错误";
                }
                else
                {
                    string parameterJson = (context.Request["parameters"] == null ? "" : context.Request["parameters"]);
                    Dictionary<string, object> parameters = JsonConvert.DeserializeObject<Dictionary<string, object>>(parameterJson);

                    SqlDatabase sqldb = new SqlDatabase(Config.TulingBuyCrmConnectString);
                    DbCommand cmd = sqldb.GetStoredProcCommand(context.Request["sp"]);
                    if (parameters != null)
                    {
                        foreach (KeyValuePair<string, object> p in parameters)
                        {
                            cmd.Parameters.Add(new SqlParameter(p.Key, p.Value));
                        }
                    }
                    Guid userid = (context.User.Identity.IsAuthenticated ? CurrentUserId : Guid.Empty);
                    cmd.Parameters.Add(new SqlParameter("userid", DbType.Guid) { Value = userid });

                    res.ResultData = sqldb.ExecuteDataSet(cmd);
                    res.ResultCode = 0;
                }
            }
            catch (Exception ex)
            {
                res.ResultCode = -1;
                res.ResultMessage = ex.Message;
            }
            context.Response.Write(JsonConvert.SerializeObject(res));
        }
    }
}